<?php
namespace app\api\controller;

use app\api\model\MultiBind;
use app\api\model\MultiOrder;
use app\api\model\ShopPayOrder;
use app\api\model\Users;
use app\api\model\UserSettle;
use app\api\model\UserStore;
use app\common\controller\Api;
use Think\Db;

class Leshua extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    //乐刷商户号
    private $merchant_id;
    //服务商编号
    private $agent_id;
    //加密key
    private $key;
    //回调key
    private $notify_key;
    //小程序id
    private $appid;
    //公众号id
    private $gzhappid;
    //请求地址
    private $gateway;
    //请求主地址
    private $site_gateway = "https://paygate.leshuazf.com/"; //生产环境
    //private $site_gateway = "https://t-paygate.lepass.cn/"; //测试环境
    //回调主地址
    private $site_url;

    public function __construct()
    {
        //服务商编号
        $this->agent_id = config("leshua.agent_id");
        // 默认商户
        $this->merchant_id = config("leshua.merchant_id");
        // md5加密key
        $this->key = config("leshua.key");
        //回调key
        $this->notify_key = config("leshua.notify_key");
        //小程序ID
        $this->appid = config("leshua.appid");
        //公众号ID
        $this->gzhappid = config("lehua.gzhappid");
        // 网关地址
        $this->gateway = $this->site_gateway."cgi-bin/lepos_pay_gateway.cgi";
        //回调主地址
        $this->site_url = config("site_url");
    }

    /**
     * 小程序统一下单
     * @param $trade_no 订单唯一编号
     * @param $totalAmount 订单总金额
     * @param $user_id 订单用户id
     * @param int $fz 是否分账：0否，1是
     * @return array|false
     */
    public function apppay($trade_no, $totalAmount,$user_id,$royalty=0)
    {
        if(empty($user_id)){
            return false;
        }
        $sub_openid = Users::where('user_id',$user_id)->value('app_openid');
        log_result('leshua',"小程序ID:".$this->appid);
        log_result('leshua',"用户openid:".$sub_openid);
        //商户号应指定订单商家的商户号
        $order = ShopPayOrder::where("order_sn",$trade_no)->find();
        if(!$order){
            return false;
        }
        $merchant_id = $this->get_merchant_id($order);
        log_result('leshua',"乐刷商户号:".$merchant_id);
        if (!$merchant_id){
            return false;
        }

        $native = array(
            "service" => "get_tdcode",
            "pay_way" => "WXZF",
            "merchant_id" => $merchant_id,
            "third_order_id" => $trade_no,
            "amount" => $totalAmount * 100,
            "jspay_flag" => "1",
            "appid" => $this->appid,
            "sub_openid" => $sub_openid, //微信JSAPI、微信小程序、支付宝JSAPI、支付宝小程序、银联JSAPI支付必填
            "notify_url" => urlencode($this->site_url."Leshua/notify"),
            //"jump_url" => urlencode($this->site_url."index.php/Mobile/Shopyiwu/yiwu_user_order"),
            "nonce_str" => self::nonce_str(),
            "royalty" => $royalty, //进行分账时传入
        );
        log_result('leshua',"统一下单入参:".json_encode($native));
        ksort($native);
        $arg = "";
        foreach ($native as $key => $val) {
            $arg .= $key . "=" . ($val) . "&";
        }
        $sign  = strtoupper(md5($arg . "key=" . $this->key));
        $native["sign"] = $sign;
        $res = $this->http_curl($this->gateway, 'post', $native);
        $res = self::xmlToArray($res);
        log_result('leshua',"统一下单返回:".json_encode($res));
        if (isset($res['resp_code'])) {
            if ($res['resp_code'] == '0') {
                if ($res['result_code'] != '0') {
                    return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                } else {
                    //下单成功成功逻辑

                    //保存乐刷订单号与商户号
                    ShopPayOrder::where("order_sn",$res['third_order_id'])->update([
                        'leshua_order_id'=>$res['leshua_order_id'],
                        'merchant_id'=>$res['merchant_id'],
                    ]);
                    $jspay_info = json_decode($res['jspay_info'],true);
                    $jspay_info['totalFee'] = $totalAmount * 100;
                    return ['status' => true, 'jspay_info' => $jspay_info, 'leshua_order_id' => $res['leshua_order_id']];
                }
            }else{
                return ['status' => false, 'error_msg' => $res['resp_msg'], 'error_code' => $res['resp_code']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }
    /**
     * 统一下单
     * @param $trade_no 订单唯一编号
     * @param $totalAmount 订单总金额
     * @param $user_id 订单用户id
     * @param int $fz 是否分账：0否，1是
     * @return array|false
     */
    public function pay($trade_no, $totalAmount,$user_id,$jspay_flag,$royalty=0)
    {
        if(empty($user_id)){
            return false;
        }
        $sub_openid = Users::where('user_id',$user_id)->value('openid');
        log_result('leshua',"用户openid:".$sub_openid);
        //商户号应指定订单商家的商户号
        $order = ShopPayOrder::where("order_sn",$trade_no)->find();
        if(!$order){
            return false;
        }
        $merchant_id = $this->get_merchant_id($order);
        log_result('leshua',"乐刷商户号:".$merchant_id);
        if (!$merchant_id){
            return false;
        }

        $native = array(
            "service" => "get_tdcode",
            "pay_way" => "WXZF",
            "merchant_id" => $merchant_id,
            "third_order_id" => $trade_no,
            "amount" => $totalAmount * 100,
            "jspay_flag" => $jspay_flag,
            "appid" => $this->appid,
            "sub_openid" => $sub_openid, //微信JSAPI、微信小程序、支付宝JSAPI、支付宝小程序、银联JSAPI支付必填
            "notify_url" => urlencode($this->site_url."index.php/Mobile/Leshua/notify"),
            "jump_url" => urlencode($this->site_url."index.php/Mobile/Shopyiwu/yiwu_user_order"),
            "nonce_str" => self::nonce_str(),
            "royalty" => $royalty, //进行分账时传入
        );
        ksort($native);
        $arg = "";
        foreach ($native as $key => $val) {
            $arg .= $key . "=" . ($val) . "&";
        }
        $sign  = strtoupper(md5($arg . "key=" . $this->key));
        $native["sign"] = $sign;
        $res = $this->http_curl($this->gateway, 'post', $native);
        $res = self::xmlToArray($res);
        halt($res);
        if (isset($res['resp_code'])) {
            if ($res['resp_code'] == '0') {
                if ($res['result_code'] != '0') {
                    return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                } else {
                    //下单成功成功逻辑

                    //保存乐刷订单号与商户号
                    M("shop_pay_order")->where("order_sn",$res['third_order_id'])->save([
                        'leshua_order_id'=>$res['leshua_order_id'],
                        'merchant_id'=>$res['merchant_id'],
                    ]);
                    //跳转支付
                    if(isset($res['td_code'])&&!empty($res['td_code'])){
                        header("Location: ".$res['td_code']);
                    }
                    if(isset($res['jspay_url'])&&!empty($res['jspay_url'])){
                        $str = str_replace(" ", "", $res['jspay_url']);
                        $str = preg_replace('/\s+/', '', $str);
                        header("Location: ".$str);
                    }
                    return ['status' => true, 'jspay_url' => $res['jspay_url'], 'leshua_order_id' => $res['leshua_order_id']];
                }
            }else{
                return ['status' => false, 'error_msg' => $res['resp_msg'], 'error_code' => $res['resp_code']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }

    /**
     * 服务器回调
     */
    public function notify()
    {
        $postStr = file_get_contents('php://input');
        log_result("leshua","支付回调-回调参数：".$postStr);
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->status != '2') {
            die($postObj->return_msg);
        }
        $native = (array) $postObj;
        log_result("leshua","支付回调-回调状态：".$native['status']);
        if ($native['status'] == 2) {
            $sign = $native['sign'];
            log_result("leshua","支付回调-回调签名：".$sign);
            unset($native['sign']);
            unset($native['error_code']);
            ksort($native);
            $arg = "";
            foreach ($native as $key => $val) {
                $arg .= $key . "=" . ($val) . "&";
            }
            $new_sign = strtolower(md5($arg . "key=" . $this->notify_key));
            log_result("leshua","支付回调-本地签名：".$new_sign);
            if ($new_sign == $sign) {
                log_result("leshua","支付回调-开启回调处理：");
                //Db::startTrans();
                $trans = true;
                $msg = "";
                //交易逻辑处理
                log_result("leshua","支付回调-交易逻辑处理：".json_encode($native));
                //$order = M("shop_pay_order")->where("order_sn",$native['third_order_id'])->lock(true)->find();
                $order = ShopPayOrder::where("order_sn",$native['third_order_id'])->find();
                if(!$order){
                    $trans = false;
                    $msg = "订单不存在";
                }
                log_result("leshua","支付回调-订单：".json_encode($order));
                //判断订单金额
                if(bcadd(bcmul($order['order_money'], 100, 2), '0', 0)!=intval($native['amount'])){
                    $trans = false;
                    $msg = "订单金额不相符";
                }
                if($order['status']==0){
                    if($order['order_type']==1){
                        //修改订单信息
                        $orderok = ShopPayOrder::where("order_sn",$native['third_order_id'])->upadte([
                            'status'=>1,
                            'pay_time'=>strtotime($native['pay_time']),
                        ]);
                        if(!$orderok){
                            $trans = false;
                            $msg = "修改订单信息失败";
                        }
                        log_result("leshua","支付回调-修改订单状态为已支付：".$orderok);
                        //结算
                        new_award($order['id']);

                        //修改总订单信息
                        $torderok = ShopPayOrder::where("id",$order['total_order_id'])->update([
                            'status'=>1,
                            'pay_time'=>strtotime($native['pay_time']),
                        ]);
                        if(!$torderok){
                            $trans = false;
                            $msg = "修改订单信息失败";
                        }
                        log_result("leshua","支付回调-修改总订单状态为已支付：".$torderok);
                        //查询是否有同一总订单的消费券订单
                        $order6 = ShopPayOrder::where(["total_order_id"=>$order['total_order_id'],'money_type'=>6])->find();
                        log_result("leshua","支付回调-是否有消费券订单：".json_encode($order6));
                        if($order6){
                            //进行支付并结算
                            $ok1 = new_finance_record_and_add_money($order6['user_id'],$order6['order_money'],6,2,203,$order6['id'],$order6['order_sn']);
                            log_result("leshua","支付回调-消费券订单扣款：".$ok1);
                            if($ok1){
                                //修改订单状态为已完成
                                $orderok6 = ShopPayOrder::where(["total_order_id"=>$order['total_order_id'],'money_type'=>6])->update([
                                    'status'=>1,
                                    'pay_time'=>time(),
                                ]);
                                if($orderok6){
                                    new_award($order6['id']);
                                }
                            }else{
                                $trans = false;
                                $msg = "消费券订单支付失败";
                            }
                        }
                        //分账
                        order_multi_apply($order['id']);
                    }else if($order['order_type']==4){
                        //修改订单信息
                        $orderok = ShopPayOrder::where("order_sn",$native['third_order_id'])->update([
                            'status'=>1,
                            'pay_time'=>strtotime($native['pay_time']),
                        ]);
                        if(!$orderok){
                            $trans = false;
                            $msg = "修改订单信息失败";
                        }
                        //修改总订单信息
                        $torderok = ShopPayOrder::where("id",$order['total_order_id'])->update([
                            'status'=>1,
                            'pay_time'=>strtotime($native['pay_time']),
                        ]);
                        if(!$torderok){
                            $trans = false;
                            $msg = "修改订单信息失败";
                        }
                        //查询是否有同一总订单的消费券订单
                        $order6 = ShopPayOrder::where(["total_order_id"=>$order['total_order_id'],'money_type'=>6])->find();
                        log_result("leshua","支付回调-是否有消费券订单：".json_encode($order6));
                        if($order6){
                            //进行支付并结算
                            $ok1 = new_finance_record_and_add_money($order6['user_id'],$order6['order_money'],6,2,203,$order6['id'],$order6['order_sn']);
                            log_result("leshua","支付回调-消费券订单扣款：".$ok1);
                            if($ok1){
                                //修改订单状态为已完成
                                $orderok6 = ShopPayOrder::where(["total_order_id"=>$order['total_order_id'],'money_type'=>6])->update([
                                    'status'=>1,
                                    'pay_time'=>time(),
                                ]);
                            }else{
                                $trans = false;
                                $msg = "消费券订单支付失败";
                            }
                        }
                    }
                }else if($order['status']==1){
                    if($order['order_type']==1){
                        //修改订单信息
                        $orderok = ShopPayOrder::where("order_sn",$native['third_order_id'])->update([
                            'pay_time'=>strtotime($native['pay_time']),
                        ]);
                        if(!$orderok){
                            $trans = false;
                            $msg = "修改订单信息失败";
                        }
                        log_result("leshua","支付回调-修改订单状态为已支付2：".$orderok);
                        //结算
                        new_award($order['id']);
                        //分账
                        order_multi_apply($order['id']);
                    }
                }
                if($trans){
                    //Db::commit();
                    die('000000');
                }else{
                    //Db::rollback();
                    die($msg);
                }
            } else {
                die('签名不一致');
            }
        }
    }

    public function scanpay($trade_no, $scanstr)
    {
        //商户号应指定订单商家的商户号
        $order = M("shop_pay_order")->where("order_sn",$trade_no)->find();
        if(!$order){
            return ['status' => false, 'error_msg' => "订单不存在", 'error_code' => -4];
        }
        $merchant_id = $order['merchant_id'];
        log_result('leshua',"被扫-乐刷商户号:".$merchant_id);
        if (!$merchant_id){
            return ['status' => false, 'error_msg' => "商号号不能为空", 'error_code' => -5];
        }

        $native = array(
            "service" => "upload_authcode",
            "auth_code" => $scanstr,
            "merchant_id" => $merchant_id,
            "third_order_id" => $trade_no,
            "amount" => $order['order_money'] * 100,
            "appid" => $this->appid,
            "body" => "被扫订单",
            "limit_pay" => "1",
            "nonce_str" => self::nonce_str(),
            "royalty"=> 1,
        );
        log_result('leshua',"被扫-入参:".json_encode($native));
        ksort($native);
        $arg = "";
        foreach ($native as $key => $val) {
            $arg .= $key . "=" . ($val) . "&";
        }
        $sign  = strtoupper(md5($arg . "key=" . $this->key));
        $native["sign"] = $sign;
        $res = $this->http_curl($this->gateway, 'post', $native);
        $res = self::xmlToArray($res);
        log_result('leshua',"被扫-返回参数:".json_encode($res));
        if (isset($res['resp_code'])) {
            if ($res['resp_code'] == '0') {
                if ($res['result_code'] != '0') {
                    return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                } else {
                    //下单成功成功逻辑
                    if($res['status']==2){
                        $notify_order = M("shop_pay_order")->where("order_sn",$res['third_order_id'])->find();
                        if(!$notify_order){
                            return ['status' => false, 'error_msg' => "未找到对应订单", 'error_code' => -1];
                        }
                        //保存总订单为已支付
                        $took = M("shop_pay_order")->where("id",$notify_order['total_order_id'])->save(['status'=>1,'pay_time'=>strtotime($res['pay_time'])]);
                        log_result('leshua',"被扫-保存总订单:".$took);
                        //保存乐刷订单号与商户号
                        $upok = M("shop_pay_order")->where("order_sn",$res['third_order_id'])->save([
                            'leshua_order_id'=>$res['leshua_order_id'],
                            'pay_code'=>$res['pay_way'],
                            'pay_time'=>strtotime($res['pay_time']),
                            'status'=>1,
                        ]);
                        if($upok){
                            //进行结算
                            $rok = new_award($notify_order['id']);
                            log_result('leshua',"被扫-结算结果:".$rok);
                            $mok = order_multi_apply($notify_order['id']);
                            log_result('leshua',"被扫-分账结果:".$mok);
                        }

                        //查询是否有同一总订单的消费券订单
                        $order6 = M("shop_pay_order")->where(["total_order_id"=>$notify_order['total_order_id'],'money_type'=>6])->find();
                        log_result("leshua","支付回调-是否有消费券订单：".json_encode($order6));
                        if($order6){
                            //进行支付并结算
                            $ok1 = new_finance_record_and_add_money($order6['user_id'],$order6['order_money'],6,2,203,$order6['id'],$order6['order_sn']);
                            log_result("leshua","支付回调-消费券订单扣款：".$ok1);
                            if($ok1){
                                //修改订单状态为已完成
                                $orderok6 = M("shop_pay_order")->where(["total_order_id"=>$order['total_order_id'],'money_type'=>6])->save([
                                    'status'=>1,
                                ]);
                                if($orderok6){
                                    new_award($order6['id']);
                                }
                            }
                        }

                        return ['status' => true, 'error_msg' => "支付成功", 'error_code' => 1];
                    }else{
                        return ['status' => false, 'error_msg' => $this->getstatusmsg($res['status']), 'error_code' => $res['status']];
                    }
                }
            }else{
                return ['status' => false, 'error_msg' => $res['resp_msg'], 'error_code' => $res['resp_code']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }
    /**
     * 交易结果查询
     * @param $trade_no 订单号
     * @return array
     */
    public function query_order($trade_no)
    {
        //dump($trade_no);
        $order = M("shop_pay_order")->where(['order_sn'=>$trade_no])->find();
        //dump($order);
        $merchant_id = $order['merchant_id']?$order['merchant_id']:$this->merchant_id;
        $native = array(
            "service" => "query_status",
            "merchant_id" => $merchant_id,
            "third_order_id" => $trade_no,
            "nonce_str" => self::nonce_str(),
        );
        ksort($native);
        $arg = "";
        foreach ($native as $key => $val) {
            $arg .= $key . "=" . ($val) . "&";
        }
        $sign  = strtoupper(md5($arg . "key=" . $this->key));
        $native["sign"] = $sign;
        //halt($native);
        $res = $this->http_curl($this->gateway, 'post', $native);
        log_result('leshua',"订单查询-返回结果：".json_encode($res));
        $res = self::xmlToArray($res);
        log_result('leshua',"订单查询-返回结果2：".json_encode($res));
        if (isset($res['resp_code'])) {
            if ($res['resp_code'] == '0') {
                if ($res['result_code'] != '0') {
                    return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                } else {
                    if($res['status']!=2){
                        return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                    }
                    //在这里编写成功逻辑
                    log_result("leshua","订单查询-返回交易订单号：".$res['third_order_id']);
                    $order = M("shop_pay_order")->where("order_sn",$res['third_order_id'])->find();
                    log_result("leshua","订单查询-订单信息：".json_encode($order));
                    if(!$order){
                        return ['status' => false, 'error_msg' => '订单不存在', 'error_code' => -2];
                    }
                    //判断订单金额
                    if(intval($order['order_money']*100)!=intval($res['amount'])){
                        return ['status' => false, 'error_msg' => '订单金额不相符', 'error_code' => -2];
                    }
                    if($order['status']==0){
                        if($order['order_type']==1){
                            //修改订单信息
                            $orderok = M("shop_pay_order")->where("order_sn",$native['third_order_id'])->save([
                                'pay_time'=>strtotime($native['pay_time']),
                            ]);
                            log_result('leshua',"订单查询-修改订单：".$orderok);
                            //结算
                            new_award($order['id']);
                            //分账
                            order_multi_apply($order['id']);
                            //查询是否有同一总订单的消费券订单
                            $order6 = M("shop_pay_order")->where(["total_order_id"=>$order['total_order_id'],'money_type'=>6])->find();
                            log_result("leshua","订单查询-是否有消费券订单：".json_encode($order6));
                            if($order6){
                                //进行支付并结算
                                $ok1 = new_finance_record_and_add_money($order6['user_id'],$order6['order_money'],6,2,203,$order6['id'],$order6['order_sn']);
                                log_result("leshua","订单查询-消费券订单扣款：".$ok1);
                                if($ok1){
                                    new_award($order6['id']);
                                }
                            }
                        }else{
                            //修改订单信息
                            $orderok = M("shop_pay_order")->where("order_sn",$native['third_order_id'])->save([
                                'status'=>1,
                                'pay_time'=>strtotime($native['pay_time']),
                            ]);
                        }
                        if($orderok){
                            return ['status' => true, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                        }else{
                            return ['status' => false, 'error_msg' => '修改订单失败', 'error_code' => -2];
                        }
                    }else if($order['status']==1){
                        if($order['order_type']==1){
                            //修改订单信息
                            $orderok = M("shop_pay_order")->where("order_sn",$native['third_order_id'])->save([
                                'pay_time'=>strtotime($native['pay_time']),
                            ]);
                            log_result('leshua',"订单查询-修改订单2：".$orderok);
                            if($orderok){
                                return ['status' => true, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                            }else{
                                return ['status' => false, 'error_msg' => '修改订单失败', 'error_code' => -2];
                            }
                            //结算
                            new_award($order['id']);
                            //分账
                            order_multi_apply($order['id']);
                            //查询是否有同一总订单的消费券订单
                            $order6 = M("shop_pay_order")->where(["total_order_id"=>$order['total_order_id'],'money_type'=>6])->find();
                            log_result("leshua","订单查询-是否有消费券订单2：".json_encode($order6));
                            if($order6){
                                //进行支付并结算
                                $ok1 = new_finance_record_and_add_money($order6['user_id'],$order6['order_money'],6,2,203,$order6['id'],$order6['order_sn']);
                                log_result("leshua","订单查询-消费券订单扣款2：".$ok1);
                                if($ok1){
                                    new_award($order6['id']);
                                }
                            }
                        }

                    }else if($order['status']==3){
                        return ['status' => true, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                    }
                }
            }else{
                return ['status' => false, 'error_msg' => $res['resp_msg'], 'error_code' => $res['resp_code']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }

    /**
     * 订单退款
     * @param $trade_no 订单号
     * @param $amount 退款金额
     * @return array
     */
    public function unified_refund($trade_no,$amount){
        $order = M("shop_pay_order")->where(['order_sn'=>$trade_no])->find();
        $native = array(
            "service" => "unified_refund",
            "merchant_id" => $order['merchant_id'],
            "third_order_id" => $trade_no,
            "leshua_order_id" => $order['leshua_order_id'],
            "merchant_refund_id" => $this->get_multi_sn(),
            "refund_amount" => $amount*100,
            "nonce_str" => self::nonce_str(),
            "notify_url" => $this->site_url."index.php/Mobile/Leshua/refund_notify",
        );
        ksort($native);
        $arg = "";
        foreach ($native as $key => $val) {
            $arg .= $key . "=" . ($val) . "&";
        }
        $sign  = strtoupper(md5($arg . "key=" . $this->key));
        $native["sign"] = $sign;
        $res = $this->http_curl($this->gateway, 'post', $native);
        $res = self::xmlToArray($res);
        if (isset($res['resp_code'])) {
            if ($res['resp_code'] == '0') {
                if ($res['result_code'] != '0') {
                    return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                } else {
                    //在这里编写成功逻辑
                    $order = M("shop_pay_order")->where('order_sn',$res['third_order_id'])->whereOr('leshua_order_id',$res['leshua_order_id'])->find();
                    if(!$order){
                        return ['status' => false, 'error_msg' => "未找到对应订单", 'error_code' => "-2"];
                    }
                    //修改订单为已取消
                    $xjok = M("shop_pay_order")->where('id',$order['id'])->save([
                        'status'=>2,
                        'finish_time'=>time(),
                    ]);
                    //修改总订单为已取消
                    $totalok = M("shop_pay_order")->where('id',$order['total_order_id'])->save([
                        'status'=>2,
                        'finish_time'=>time(),
                    ]);
                    //修改消费券订单为已取消
                    $ywqok = M("shop_pay_order")->where(['total_order_id'=>$order['total_order_id'],'money_type'=>6])->save([
                        'status'=>2,
                        'finish_time'=>time(),
                    ]);
                    if(!$xjok || !$totalok || !$ywqok){
                        return ['status' => false, 'leshua_order_id' => $res['leshua_order_id']];
                    }else{
                        return ['status' => true, 'leshua_order_id' => $res['leshua_order_id']];
                    }
                }
            }else{
                return ['status' => false, 'error_msg' => $res['resp_msg'], 'error_code' => $res['resp_code']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }

    /**
     * 退款回调地址
     */
    public function refund_notify()
    {
        $postStr = file_get_contents('php://input');
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->status != '2') {
            die($postObj->return_msg);
        }

        $native = (array) $postObj;
        if ($native['status'] == 2) {
            $sign = $native['sign'];
            unset($native['sign']);
            unset($native['error_code']);
            ksort($native);
            $arg = "";
            foreach ($native as $key => $val) {
                $arg .= $key . "=" . ($val) . "&";
            }
            $new_sign = strtoupper(md5($arg . "key=" . $this->key));
            if ($new_sign == $sign) {
                //交易逻辑处理
                log_result("leshua",json_encode($native));

                die('000000');
            } else {
                die('签名不一致');
            }
        }
    }

    /**
     * 退款查询
     * @param $trade_no 订单号
     * @return array
     */
    public function unified_query_refund($trade_no){
        $native = array(
            "service" => "unified_query_refund",
            "merchant_id" => $this->merchant_id,
            "third_order_id" => $trade_no,
            "merchant_refund_id" => $trade_no,
            "nonce_str" => self::nonce_str(),
            "notify_url" => $this->site_url."index.php/Mobile/Leshua/refund_notify",
        );
        ksort($native);
        $arg = "";
        foreach ($native as $key => $val) {
            $arg .= $key . "=" . ($val) . "&";
        }
        $sign  = strtoupper(md5($arg . "key=" . $this->key));
        $native["sign"] = $sign;
        $res = $this->http_curl($this->gateway, 'post', $native);
        $res = self::xmlToArray($res);
        if (isset($res['resp_code'])) {
            if ($res['resp_code'] == '0') {
                if ($res['result_code'] != '0') {
                    //在这里编写成功逻辑
                    return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                } else {
                    return ['status' => true, 'jspay_url' => $res['jspay_url'], 'leshua_order_id' => $res['leshua_order_id']];
                }
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }

    /**
     * 关闭订单
     * @param $trade_no 订单号
     * @return array
     */
    public function close_order($trade_no){
        $native = array(
            "service" => "close_order",
            "merchant_id" => $this->merchant_id,
            "third_order_id" => $trade_no,
            "nonce_str" => self::nonce_str(),
        );
        ksort($native);
        $arg = "";
        foreach ($native as $key => $val) {
            $arg .= $key . "=" . ($val) . "&";
        }
        $sign  = strtoupper(md5($arg . "key=" . $this->key));
        $native["sign"] = $sign;
        $res = $this->http_curl($this->gateway, 'post', $native);
        $res = self::xmlToArray($res);
        if (isset($res['resp_code'])) {
            if ($res['resp_code'] == '0') {
                if ($res['result_code'] != '0') {
                    //在这里编写成功逻辑
                    return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                } else {
                    return ['status' => true, 'jspay_url' => $res['jspay_url'], 'leshua_order_id' => $res['leshua_order_id']];
                }
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }
    //分账
    public function multi_apply($order,$shareDetail){
        log_result('leshua',"分账-原订单：".$order['id']);

        //检测分账绑定关系
        $item=array();
        foreach ($shareDetail as $k=>$v){
            array_push($item,$v['merchantId']);
        }
        $this->bind($order['merchant_id'],$item);

        $nulti_sn = $this->get_multi_sn();
        //乐刷不对测试环境的交易订单进行清分、入账和出款，请直接在生产环境进行调试。
        $url = "https://saas-mch.leshuazf.com/api/share-merchant/multi-apply";
        $public = array(
            "agentId" => $this->agent_id,
            "version" => "2.0",
            "reqSerialNo" => $nulti_sn,
        );

        $data = array(
            "merchantId" => empty($order['merchant_id'])?$this->get_merchant_id($order):$order['merchant_id'],
            "leshuaOrderId" => $order['leshua_order_id'],
            "thirdOrderId" => $order['order_sn'],
            "thirdRoyaltyId" => $nulti_sn,
            "shareDetail" => $shareDetail,
            "Remark" => "分账",
        );
        log_result('leshua',"分账-分账关键参数："."服务号-".$this->agent_id.",商户号-".$this->get_merchant_id($order));
        log_result('leshua',"分账-分账入参：".json_encode($data));
        $sign  = base64_encode(strtolower(md5("lepos".$this->key.json_encode($data))));
        $public["sign"] = $sign;
        $public["data"] = json_encode($data);
        $res = $this->http_curl($url, 'post', $public);
        log_result('leshua',"分账-分账返回：".$res);
        $res = json_decode($res,true);
        if (isset($res['respCode'])) {
            if ($res['respCode'] == '000000') {
                $resdata = $res['data'];
                log_result('leshua',"分账-分账返回数据：".json_encode($resdata));
                if ($resdata['retcode'] != '0') {
                    return ['status' => false, 'error_msg' => $resdata['retmsg'], 'error_code' => $resdata['retcode']];
                } else {
                    //在这里编写成功逻辑
                    log_result('leshua',"分账-分账成功数据：".json_encode($resdata));
                    //标志订单已分账
                    ShopPayOrder::where(['leshua_order_id'=>$resdata['leshua_order_id']])->update(['is_account'=>$resdata['royalty_status']]);
                    //标志分账订单
                    MultiOrder::where(['leshua_order_id'=>$resdata['leshua_order_id']])->update(['status'=>$resdata['royalty_status'],'retcode'=>$resdata['retcode'],'retmsg'=>$resdata['retmsg']]);
                    //记录分账用户收益
                    $muorder = MultiOrder::where(['leshua_order_id'=>$resdata['leshua_order_id'],'status'=>1])->find();
                    log_result('leshua',"分账-分账订单信息：".json_encode($muorder));
                    if($muorder){
                        $mudetail = json_decode($muorder['share_detail'],true);
                        foreach ($mudetail as $k=>$v){
                            $muuserid = Users::where('merchant_id',$v['merchantId'])->value('user_id');
                            if(!$muuserid){
                                $muuserid = UserStore::where('merchant_id',$v['merchantId'])->value('user_id');
                            }
                            if($muuserid&&$v['amount']>0){
                                $order = ShopPayOrder::where(['leshua_order_id'=>$resdata['leshua_order_id']])->find();
                                $arrconfig = config("finance_msg");
                                $msg_type = array_search($v['remark'],$arrconfig);
                                $recordok = new_finance_record($muuserid,($v['amount']/100),1,1,$msg_type,$order['id'],0,$order['order_sn']);
                            }
                        }
                    }

                    return ['status' => true, 'error_msg' => $resdata['retmsg'], 'error_code' => $resdata['retcode']];
                }
            }else{
                return ['status' => false, 'error_msg' => $res['respMsg'], 'error_code' => $res['respCode']];
            }
        } else {
            return ['status' => false, 'error_msg' => '分账异常', 'error_code' => -1];
        }
    }

    //分账订单查询
    public function multi_query($trade_no){
        $url = "https://saas-mch.leshuazf.com/api/share-merchant/multi-query";
        $nulti_sn = $this->get_multi_sn();
        //dump($trade_no);
        $order = M("shop_pay_order")->where(['order_sn'=>$trade_no])->find();
        //dump($order);
        $merchant_id = $order['merchant_id']?$order['merchant_id']:$this->merchant_id;
        $public = array(
            "agentId" => $this->agent_id,
            "version" => "1.0",
            "reqSerialNo" => $nulti_sn,
        );
        $data = array(
            "merchantId" => $merchant_id,
            "leshuaOrderId" => $order['leshua_order_id'],
            "allRoyaltyFlag" => 1,
        );
        log_result('leshua',"分账查询-分账关键参数："."服务号-".$this->agent_id.",商户号-".$merchant_id);
        log_result('leshua',"分账查询-分账入参：".json_encode($data));
        $sign  = base64_encode(strtolower(md5("lepos".$this->key.json_encode($data))));
        $public["sign"] = $sign;
        $public["data"] = json_encode($data);
        $res = $this->http_curl($url, 'post', $public);
        log_result('leshua',"分账查询-分账返回：".$res);
        $res = json_decode($res,true);
        //halt($res);
        if (isset($res['respCode'])) {
            if ($res['respCode'] == '000000') {
                $resdata = $res['data'];
                if ($resdata['retcode'] != '0') {
                    return ['status' => false, 'error_msg' => $resdata['retmsg'], 'error_code' => $resdata['retcode']];
                } else {
                    return ['status' => true, 'error_msg' => $resdata['retmsg'], 'error_code' => $resdata['retcode'],'data'=>$resdata];
                }
            }else{
                return ['status' => false, 'error_msg' => $res['respMsg'], 'error_code' => $res['respCode']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }

    //分账订单退款
    public function multi_refund($order){

        $nulti_sn = $this->get_multi_sn();
        $url = "https://saas-mch.leshuazf.com/api/share-merchant/refund";
        $public = array(
            "agentId" => $this->agent_id,
            "version" => "1.0",
            "reqSerialNo" => $nulti_sn,
        );

        $data = array(
            "merchantId" => $order['merchant_id'],
            "leshuaOrderId" => $order['leshua_order_id'],
            "thirdOrderId" => $order['order_sn'],
            "refundAmount" => $order['order_money']*100,
            "thirdRefundId" => $nulti_sn,
            "refundDetails" => [
                'accountId' => $order['merchant_id'],
                'amount' => $order['order_money']*100,
                'remark' => '用户退款'
            ],
        );

        $sign  = base64_encode(strtolower(md5("lepos".$this->key.json_encode($data))));
        $public["sign"] = $sign;
        $public["data"] = json_encode($data);
        $res = $this->http_curl($url, 'post', $public);

        $res = json_decode($res,true);
        if (isset($res['respCode'])) {
            if ($res['respCode'] == '000000') {
                $resdata = $res['data'];
                if ($resdata['retcode'] != '0') {
                    return ['status' => false, 'error_msg' => $resdata['retmsg'], 'error_code' => $resdata['retcode']];
                } else {
                    //在这里编写成功逻辑
                    $order = M("shop_pay_order")->where(['leshua_order_id'=>$resdata['leshua_order_id']])->find();
                    //标志订单已退款
                    M("shop_pay_order")->where(['leshua_order_id'=>$resdata['leshua_order_id']])->save(['status'=>2,'finish_time'=>time()]);
                    //标志总订单已退款
                    M("shop_pay_order")->where(['id'=>$order['total_order_id']])->save(['status'=>2,'finish_time'=>time()]);
                    //查询是否有消费券订单
                    $order6 = M("shop_pay_order")->where(['total_order_id'=>$order['total_order_id'],'money_type'=>6])->find();
                    if($order6){
                        //退回金额
                        $logok = new_finance_record_and_add_money($order6['user_id'],$order6['order_money'],$order6['money_type'],1,501,$order6['id'],$order6['order_sn']);
                        //修改订单
                        $ywok = M("shop_pay_order")->where(['id'=>$order6['id']])->save([
                            'status'=>2,
                            'finish_time'=>time(),
                        ]);
                    }
                    return ['status' => true, 'error_msg' => $resdata['retmsg'], 'error_code' => $resdata['retcode']];
                }
            }else{
                return ['status' => false, 'error_msg' => $res['respMsg'], 'error_code' => $res['respCode']];
            }
        } else {
            return ['status' => false, 'error_msg' => '分账异常', 'error_code' => -1];
        }
    }

    //分账电子协议签订
    public function agreement($order_id){
        //$url = "http://t-saas-mch.lepass.cn/api/share-merchant/elec-contract-accredit"; //测试环境
        $url = "https://saas-mch.leshuazf.com/api/share-merchant/elec-contract-accredit"; //生产环境
        //获取协议订单
        $order = M("agreement_order")->where("id",$order_id)->find();
        if(!$order){
            return false;
        }

        log_result('leshua',"协议签订-订单：".json_encode($order));
        //业务参数
        $data = [
            'merchantId'=>M("user_store")->where('id',$order['store_id'])->value("merchant_id"),
            'baseInfo'=>['shareRole'=>0],
            'otherInfo'=>[
                "sharePercent"=>C("payconfig.share_percent"),
                "authTypes"=>"1,2",
                "callBackUrl"=>$this->site_url."index.php/Mobile/Leshua/agreement_notify",
            ],
        ];
        log_result('leshua',"协议签订-入参：".json_encode($data));
        //公共参数
        $obj['agentId'] = $this->agent_id;
        $obj['version'] = "1.0";
        $obj['reqSerialNo'] = $order['reqSerialNo'];
        $obj['data'] = json_encode($data);
        $sign= base64_encode(strtolower(md5("lepos".$this->key.json_encode($data))));
        $obj['sign'] = $sign;
        $res = $this->http_curl($url, 'post', $obj);
        log_result('leshua',"协议签订-返回参数1：".$res);
        $res = json_decode($res,true);
        if (isset($res['respCode'])) {
            if ($res['respCode'] == '000000') {
                //下单成功成功逻辑
                $str = str_replace(" ", "", $res['data']['contractUrl']);
                $str = preg_replace('/\s+/', '', $str);
                //log_result('leshua',"跳转2：".$str);
                // 发送请求到目标服务器
                //$response = file_get_contents($str);
                // 添加CORS头允许前端访问
                //header('Access-Control-Allow-Origin: https://lm.gxdyyg.cn');
                //header("Location: ".$str);
                return ['status' => true, 'jspay_url' => $str, 'merchantId' => $res['data']['merchantId']];
            }else{
                return ['status' => false, 'error_msg' => $res['respMsg'], 'error_code' => $res['respCode']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }
    //电子协议回调
    public function agreement_notify(){
        $postStr = file_get_contents('php://input');
        log_result("leshua","协议回调-回调参数：".$postStr);
        log_result("leshua","协议回调-回调参数：".json_encode($postStr));
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        log_result("leshua","协议回调-回调参数2：".$postObj);
        log_result("leshua","协议回调-回调参数2：".json_encode($postObj));
        if ($postObj === false) {
            die('parse xml error');
        }
    }
    //协议查询
    public function accreditQuery($merchantId){
        $url = "https://saas-mch.leshuazf.com/api/share-merchant/accreditQuery";
        $nulti_sn = $this->get_multi_sn();

        $public = array(
            "agentId" => $this->agent_id,
            "version" => "1.0",
            "reqSerialNo" => $nulti_sn,
        );
        $data = array(
            "merchantId" => $merchantId,
        );
        $sign  = base64_encode(strtolower(md5("lepos".$this->key.json_encode($data))));
        $public["sign"] = $sign;
        $public["data"] = json_encode($data);
        $res = $this->http_curl($url, 'post', $public);
        $res = json_decode($res,true);
        //dump($res);
        if (isset($res['respCode'])) {
            if ($res['respCode'] == '000000') {
                return ['status' => true, 'error_msg' => $res['respMsg'], 'error_code' => $res['respCode'],'data'=>$res['data']];
            }else{
                return ['status' => false, 'error_msg' => $res['respMsg'], 'error_code' => $res['respCode']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }
    /**
     * 分账绑定
     * @param $main 分账方
     * @param $item 分账接收方
     */
    public function bind($main,$item){
        if(!is_array($item)){
            $item = (array)$item;
        }

        foreach ($item as $v){
            $bok = MultiOrder::where(['main'=>$main,'item'=>$v])->find();
            if(!$bok){
                $reqSerialNo = date("YmdHis").rand(10000,99999);
                MultiOrder::create([
                    'main'=>$main,
                    'item'=>$v,
                    "reqSerialNo" => $reqSerialNo,
                    'createtime'=>time(),
                ]);
                $this->multi_bind($main,$v,$reqSerialNo);
            }
        }
    }
    public function multi_bind($merchantId1,$merchantId2,$reqSerialNo){
        $url = "https://saas-mch.leshuazf.com/api/share-merchant/bind";
        $public = array(
            "agentId" => $this->agent_id,
            "version" => "1.0",
            "reqSerialNo" => $reqSerialNo,
        );
        $data = array(
            "merchantId1" => $merchantId1,
            "merchantId2" => $merchantId2,
            "protocolPic"=>config("site_url")."static/images/agreement.jpg"
        );
        $sign  = base64_encode(strtolower(md5("lepos".$this->key.json_encode($data))));
        $public["sign"] = $sign;
        $public["data"] = json_encode($data);
        $res = $this->http_curl($url, 'post', $public,"application/x-www-form-urlencoded");
        $res = json_decode($res,true);

        if (isset($res['respCode'])) {
            if ($res['respCode'] == '000000') {
               MultiBind::where('reqSerialNo',$res['reqSerialNo'])->update(['status'=>1]);
            }else{
                return ['status' => false, 'error_msg' => $res['respMsg'], 'error_code' => $res['respCode']];
            }
        } else {
            return ['status' => false, 'error_msg' => '分账异常', 'error_code' => -1];
        }
    }

    /**
     * 订单清分结果查询
     * @param $order
     */
    public function getOrderSettleInfo($order){
        $url = "https://saas-mch.leshuazf.com/apiv2/merchant/getOrderSettleInfo";
        $public = array(
            "agentId" => $this->agent_id,
            "version" => "2.0",
            "reqSerialNo" => date("YmdHis").rand(10000,99999),
        );
        $data = array(
            "merchantId" => $order['merchant_id'],
            "orderId" => $order['leshua_order_id'],
            "tradeType"=>"2",
        );
        $sign  = base64_encode(strtolower(md5("lepos".$this->key.json_encode($data))));
        $public["sign"] = $sign;
        $public["data"] = json_encode($data);
        dump($public);
        $res = $this->http_curl($url, 'post', $public);
        $res = json_decode($res,true);
        halt($res);
        if (isset($res['respCode'])) {
            if ($res['respCode'] == '000000') {
                //M("multi_bind")->where('reqSerialNo',$res['reqSerialNo'])->save(['status'=>1]);
            }else{
                return ['status' => false, 'error_msg' => $res['respMsg'], 'error_code' => $res['respCode']];
            }
        } else {
            return ['status' => false, 'error_msg' => '分账异常', 'error_code' => -1];
        }
    }
    //商户打款结算查询
    public function settle_query($user_id){
        $url = "https://saas-combine.leshuazf.com/open-api/agent/merchant-settlement-order";
        $merchant_id = Users::where('user_id',$user_id)->value('merchant_id');
        if(empty($merchant_id)){
            $merchant_id = UserStore::where('user_id',$user_id)->value('merchant_id');
        }
        if(empty($merchant_id)){
            return ['status' => false, 'error_msg' => "商户不存在", 'error_code' => -1];
        }
        $public = array(
            "agentId" => $this->agent_id,
            "version" => "1.0",
            "reqSerialNo" => self::nonce_str(),
        );
        $data = array(
            "merchantId" => $merchant_id,
            //"date" => date("Y-m-d"),
            "date" => date("2025-09-18"),
            "type" => "D1",
            "state" => 1,
            "pageNo" => 1,
        );

        $sign  = base64_encode(strtolower(md5("lepos".$this->key.json_encode($data))));
        $public["sign"] = $sign;
        $public["data"] = json_encode($data);
        $res = $this->http_curl($url, 'post', $public);
        $res = json_decode($res,true);
        if (isset($res['error_code'])) {
            if ($res['error_code'] == '0') {
                if(count($res['list'])<=0){
                    return ['status' => false, 'error_msg' => "暂无数据", 'error_code' => -2,'data'=>0];
                }
                $resdata = $res['list'][0];
                //判断当天是否已有结算
                $usersettle = UserSettle::where(['user_id'=>$user_id,'settleDate'=>$resdata['settleDate']])->find();
                if($usersettle){
                    return ['status' => true, 'error_msg' => "加载成功", 'error_code' => 1,'data'=>$usersettle['bankretTime']];
                }else{
                    //不存在，则生成新数据
                    $resdata['user_id'] = $user_id;
                    $resdata['bankretTime'] = strtotime($resdata['bankretTime']);
                    //halt($resdata);
                    UserSettle::create($resdata,true);
                    return ['status' => true, 'error_msg' => "加载成功", 'error_code' => 1,'data'=>$resdata['bankretTime']];
                }
            }else{
                return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
            }
        } else {
            return ['status' => false, 'error_msg' => '查询异常', 'error_code' => -1];
        }
    }

    //随机32位字符串
    public static function nonce_str()
    {
        $result = '';
        $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
        for ($i = 0; $i < 32; $i++) {
            $result .= $str[rand(0, 48)];
        }
        return $result;
    }

    function http_curl($url = "", $type = 'get', $arr = '',$head = '')
    {
        $ch = curl_init();
        //2.设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url); //设置我们的url
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //curl_exec执行成功则返回执行结果
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr); //将$arr发送给$url
        }
        curl_setopt($ch,CURLINFO_CONTENT_TYPE,"application/x-www-form-urlencoded");
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    /**
     * xml转换成数组
     * @param $xml
     * @return array|mixed|object
     */
    public static function xmlToArray($xml)
    {
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }

    //获取支付商户号
    private function get_merchant_id($order){
        //获取店铺
        $shop =UserStore::where("user_id",$order['shop_user_id'])->find();
        if(!$shop){
            return false;
        }
        //判断店是收券还是收现金
        if($order['shop_money_type']==2){ //店铺收现金
            return $shop['merchant_id'];
        }
        return $this->merchant_id;
    }
    /**
     * 生成分账订单号
     * @return string
     */
    public function get_multi_sn()
    {
        $multi_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $multi_sn = date("YmdHis").rand(10000,99999);
            $order_sn_count = M('multi_order')->where(array('multi_sn' => $multi_sn))->count();
            if($order_sn_count == 0)
                break;
        }
        return $multi_sn;
    }

    public function getstatusmsg($status){
        $arr = [
            '0'=>'支付中',
            '2'=>'支付成功',
            '6'=>'订单关闭',
            '8'=>'支付失败',
            '10'=>'退款中',
            '11'=>'退款成功',
            '12'=>'退款失败',
        ];
        if(empty($status)){
            return null;
        }else{
            return $arr[$status];
        }

    }

    public function query_openid($auth_code){
        $native = array(
            "service" => "query_openid",
            "merchant_id" => $this->merchant_id,
            "auth_code" => $auth_code,
            "appid" => $this->appid,
            "nonce_str" => self::nonce_str(),
        );
        ksort($native);
        $arg = "";
        foreach ($native as $key => $val) {
            $arg .= $key . "=" . ($val) . "&";
        }
        $sign  = strtoupper(md5($arg . "key=" . $this->key));
        $native["sign"] = $sign;
        $res = $this->http_curl($this->gateway, 'post', $native);
        $res = self::xmlToArray($res);
        if (isset($res['resp_code'])) {
            if ($res['resp_code'] == '0') {
                if ($res['result_code'] != '0') {
                    return ['status' => false, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code']];
                } else {
                    $data['merchant_id'] = $res['merchant_id'];
                    $data['third_order_id'] = $res['third_order_id'];
                    $data['openid'] = $res['openid'];
                    $data['sub_openid'] = $res['sub_openid'];
                    return ['status' => true, 'error_msg' => $res['error_msg'], 'error_code' => $res['error_code'], 'data' => $data];
                }
            }else{
                return ['status' => false, 'error_msg' => $res['resp_msg'], 'error_code' => $res['resp_code']];
            }
        } else {
            return ['status' => false, 'error_msg' => '支付异常', 'error_code' => -1];
        }
    }
}
